package com.nnxy.worktostudy.security.filter;

import com.nnxy.worktostudy.security.security.TokenManager;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * @Author : lu'qz
 * @create 2021/9/22 18:14
 */
public class TokenAuthFilter extends BasicAuthenticationFilter {
    private TokenManager tokenManager;

    public TokenAuthFilter(AuthenticationManager authenticationManager, TokenManager tokenManager) {
        super(authenticationManager);
        this.tokenManager = tokenManager;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        UsernamePasswordAuthenticationToken authRequest = getAuthentication(request);
        if (authRequest != null) {
            SecurityContextHolder.getContext().setAuthentication(authRequest);
        }
        chain.doFilter(request,response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token != null) {
            Long id = tokenManager.verify(token);
            String username = request.getSession().getAttribute(id.toString()).toString();
            List<String> permissionList = (List<String>) request.getSession().getAttribute(username);
            Collection<GrantedAuthority> authority = new ArrayList<>();
            for (String permission: permissionList) {
                SimpleGrantedAuthority auth = new SimpleGrantedAuthority(permission);
                authority.add(auth);
            }

            return new UsernamePasswordAuthenticationToken(username,token,authority);
        } else {
            return null;
        }
    }
}
